/***************************************************************************
 *   Copyright (C) 2007 by Jiří Němec                                  	   *
 *   nemec.jiri@gmail.com                                                  *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "vytvorslovnik.h"

#include <QThread>
#include <QRegExp>
#include <QBuffer>
#include <QByteArray>

#include "zlib.h"
#define CHUNK 16384


SlovnikData::SlovnikData(HashTabulka * t,QString confDir) {
    this->indexTabulka = t;
    this->konfiguraceAdresar = confDir;
}

void SlovnikData::run() {
    QDir dir(this->konfiguraceAdresar);
    if (!dir.exists()) {
        if (dir.mkdir(this->konfiguraceAdresar));
            //qDebug() << "vytvoren adresar " << dir.absolutePath();
    }

    this->httpNazevSouboru = this->konfiguraceAdresar+QDir::separator()+"slovnik.zcu.gz";
    this->lokalniNazevSouboru = this->konfiguraceAdresar+QDir::separator()+"slovnik.zcu";
    this->indexNazevSouboru = this->konfiguraceAdresar+QDir::separator()+"slovnik.zcu.bix";
    //qDebug() << this->lokalniNazevSouboru;

    if (QFile::exists(this->lokalniNazevSouboru)) this->vytvorIndex(false);
    else stahnout();
    exec();
}

void SlovnikData::stahnout() {
    httpSoubor.setFileName(httpNazevSouboru);
    httpSoubor.flush();
    if ( !httpSoubor.open ( QIODevice::WriteOnly ) ) {
        emit zmenaStatusu (QString::fromUtf8( "Nejde zapisovat na disk" ));
    }
    http.setHost ( "slovnik.zcu.cz");
    emit zmenaStatusu ( QString::fromUtf8("Stahuji slovník." ));
    httpGetId = http.get( "/files/slovnik_data_utf8.txt.gz" ,&httpSoubor );
    connect ( &http, SIGNAL ( done ( bool ) ),this, SLOT ( stahovaniUkonceno ( bool ) ) );
}

void SlovnikData::stahovaniUkonceno ( bool error ) {
    if ( error )
        emit zmenaStatusu ( QString::fromUtf8("Doslo k problému při stahování slovníku") );
    else {
        emit zmenaStatusu ( QString::fromUtf8("Slovník byl stažen") );
        httpSoubor.close();
        gzFile file;
        file = gzopen (QFile::encodeName(httpNazevSouboru).data(), "rb" );

        if ( !file ) {
            //qDebug ( "Can't open file" );
            emit zmenaStatusu (QString::fromUtf8("Došlo k problému při konverzi slovníkových dat" ));
            return;
        }
        QFile output(lokalniNazevSouboru);
        output.flush();
        if ( !output.open ( QIODevice::WriteOnly) ) {
            emit zmenaStatusu (QString::fromUtf8( "Nejde zapisovat na disk" ));
        }
        char bf[16384];
        while ( int readBytes =  gzread ( file, bf, 16384 ) ) {
            output.write( QByteArray ( bf, readBytes ) );
        }
        gzclose ( file );
        output.close();
        QDir r;
        r.remove(httpNazevSouboru);
        emit zmenaStatusu ( QString::fromUtf8("Slovník byl rozbalen") );
        this->vytvorIndex(true);
    }
}

void SlovnikData::vytvorIndex(bool force) {
    //force = true;
    if (QFile::exists(this->indexNazevSouboru) && !force) {
        emit zmenaStatusu (QString::fromUtf8( "Načítám index" ));
        this->indexTabulka->nacti(this->indexNazevSouboru);
    } else {
        QFile input(lokalniNazevSouboru);
        if ( !input.open ( QIODevice::ReadOnly | QIODevice::Text) ) {
            emit zmenaStatusu (QString::fromUtf8( "Nejde cist z disku" ));
        }
        emit zmenaStatusu (QString::fromUtf8( "Indexuji" ));
        QRegExp regExp("^([^\t#]*)\t([^\t]*)\t([^\t]*)\t([^\t]*)\t([^\n]*)");
        qint64 pos = 0;
        while (!input.atEnd()) {
            pos = input.pos();
            if (regExp.indexIn(QString::fromUtf8(input.readLine())) > -1) {
                if (regExp.cap(1).trimmed().length() > 0 &&  regExp.cap(2).trimmed().length()) {
                    this->indexTabulka->pridej(regExp.cap(1),pos);
                    this->indexTabulka->pridej(regExp.cap(2),pos);
                }
            }
        }
        this->indexTabulka->uloz(this->indexNazevSouboru);
    }
    emit zmenaStatusu (QString::fromUtf8( "Slovník je připraven" ));
}

void SlovnikData::pridat(Radek r) {
    QFile output(this->lokalniNazevSouboru);

    if ( !output.open (QIODevice::Append | QIODevice::Text) ) {
        emit zmenaStatusu (QString::fromUtf8( "Nejde zapisovat na disk" ));
    }
    qint64 pos = output.pos();
    output.write(QByteArray(QString(r.anglicky + "\t" + r.cesky + "\t" + r.poznamky + "\t" + r.specPoznamky + "\t" + r.autor + "\n").toUtf8()));
    output.close();
    this->indexTabulka->pridej(r.cesky,pos);
    this->indexTabulka->pridej(r.anglicky,pos);
    this->indexTabulka->uloz(this->indexNazevSouboru);
}


